package com.xt.purchasingsystem.service.impl.productionManagementServiceImpl;

import com.xt.purchasingsystem.dto.InternalDto;
import com.xt.purchasingsystem.dto.MProcedureVoAndModuleVoDto;
import com.xt.purchasingsystem.dto.SubmitRegisterDto;
import com.xt.purchasingsystem.mapper.*;
import com.xt.purchasingsystem.model.*;
import com.xt.purchasingsystem.service.productionManagementService.InternalpromanagementService;
import com.xt.purchasingsystem.utils.PageBean;
import com.xt.purchasingsystem.utils.Result;
import com.xt.purchasingsystem.utils.ResultFactory;
import com.xt.purchasingsystem.utils.SerialNumberUtil;
import com.xt.purchasingsystem.vo.MProcedureModuleVo;
import com.xt.purchasingsystem.vo.MProcedureVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional

public class InternalpromanagementServicelmpl implements InternalpromanagementService {
    @Autowired
    private MManufactureMapper mManufactureMapper;
    @Autowired
    private MProcedureMapper mProcedureMapper;
    @Autowired
    private MProcedureModuleMapper mProcedureModuleMapper;
    @Autowired
    private MProceduringMapper mProceduringMapper;
    @Autowired
    private MProcedureModulingMapper mProcedureModulingMapper;
    @Autowired
    private SGatherMapper sGatherMapper;
    @Autowired
    private SGatherDetailsMapper sGatherDetailsMapper;
    @Autowired
    private SCellMapper sCellMapper;
    @Autowired
    private DFileMapper dFileMapper;

    @Override
    public Result getAllMManufacture(InternalDto internalDto) {
        int rowCount = mManufactureMapper.queryRowCountByAllMManufacture(internalDto);
        PageBean pageBean = new PageBean(internalDto.getPageSize(), internalDto.getCurrNo(), rowCount);
        internalDto.setCurrNo(pageBean.getStart());
        internalDto.setPageSize(pageBean.getEnd());
        List<MManufacture> manufactures = mManufactureMapper.getAllMManufacture(internalDto);
        pageBean.setPageList(manufactures);
        return ResultFactory.buildSuccessResult("查询成功", pageBean);
    }


    @Override
    public Result getAllCheckNoMManufacture(InternalDto internalDto) {
        int rowCount = mManufactureMapper.queryRowCountByCheckNoAllMManufacture(internalDto);
        PageBean pageBean = new PageBean(internalDto.getPageSize(), internalDto.getCurrNo(), rowCount);
        internalDto.setCurrNo(pageBean.getStart());
        internalDto.setPageSize(pageBean.getEnd());
        List<MManufacture> manufactures = mManufactureMapper.getAllCheckNoMManufacture(internalDto);
        pageBean.setPageList(manufactures);
        return ResultFactory.buildSuccessResult("查询成功", pageBean);
    }

    @Override
    public Result updateCheckTag(String productId) {
        int i = mManufactureMapper.updateCheckTag(productId);
        if (i == 1) {
            return ResultFactory.buildSuccessResult("审核通过");
        } else {
            return ResultFactory.buildFailResult("审核失败");
        }
    }

    @Override
    public Result queryAllproductionRegistrationByPage(Integer currNo, Integer pageSize) {
        int rowCount = mManufactureMapper.rowCountRegisteredTobe();
        PageBean pageBean = new PageBean(pageSize, currNo, rowCount);
        List<MManufacture> allByRegisteredTobe = mManufactureMapper.getAllByRegisteredTobe(pageBean.getStart(), pageBean.getEnd());
        pageBean.setPageList(allByRegisteredTobe);
        return ResultFactory.buildSuccessResult("查询成功", pageBean);
    }

    @Override
    public Result getAllMProcedureAndModulesById(Integer id, String type) {

        if (type.equals("register")) {
            //登记
            List<MProcedureVoAndModuleVoDto> mprocedureAndModuleDtos = new ArrayList<>();
            List<MProcedureVo> allVoByParentId = mProcedureMapper.getAllVoByParentId(id);
            if (allVoByParentId != null && allVoByParentId.size() > 0) {
                for (MProcedureVo mProcedure : allVoByParentId) {
                    MProcedureVoAndModuleVoDto mProcedureAndModuleDto = new MProcedureVoAndModuleVoDto();
                    List<MProcedureModuleVo> allByParentId1 = mProcedureModuleMapper.getAllVoByParentId(mProcedure.getId());
                    mProcedureAndModuleDto.setMprocedureVo(mProcedure);
                    mProcedureAndModuleDto.setMprocedureModuleVos(allByParentId1);
                    mprocedureAndModuleDtos.add(mProcedureAndModuleDto);
                }
            }
            return ResultFactory.buildSuccessResult("查询成功", mprocedureAndModuleDtos);
        } else {
            //复核
            List<MProcedureVoAndModuleVoDto> mprocedureAndModuleDtos = new ArrayList<>();
            List<MProcedureVo> allVoByParentId = mProcedureMapper.getAllVoByParentId(id);

            if (allVoByParentId != null && allVoByParentId.size() > 0) {
                List<MProceduring> allNotCheckByMmanufactureId = mProceduringMapper.getAllNotCheckByMmanufactureId(id);

                for (MProcedureVo mProcedure : allVoByParentId) {
                    MProcedureVoAndModuleVoDto mProcedureAndModuleDto = new MProcedureVoAndModuleVoDto();

                    for (MProceduring mProceduring : allNotCheckByMmanufactureId) {
                        if (mProcedure.getProcedureName().equals(mProceduring.getProcedureName())) {
                            mProcedure.setNumberOfHours(mProceduring.getLabourHourAmount());
                            List<MProcedureModuling> allByMproceduringId = mProcedureModulingMapper.getAllByMproceduringId(mProceduring.getId());

                            List<MProcedureModuleVo> allByParentId1 = mProcedureModuleMapper.getAllVoByParentId(mProcedure.getId());
                            System.out.println(allByParentId1);
                            mProcedure.setId(mProceduring.getId());

                            if (allByMproceduringId != null && allByMproceduringId.size() > 0) {

                                for (MProcedureModuleVo mProcedureModuleVo : allByParentId1) {
                                    for (MProcedureModuling mProcedureModuling : allByMproceduringId) {
                                        if (mProcedureModuleVo.getProductName().equals(mProcedureModuling.getProductName())) {
                                            mProcedureModuleVo.setNumber(mProcedureModuling.getAmount());
                                            mProcedureModuleVo.setId(mProcedureModuling.getId());
                                        }
                                    }
                                }
                                mProcedureAndModuleDto.setMprocedureModuleVos(allByParentId1);

                            } else {
                                mProcedureAndModuleDto.setMprocedureModuleVos(allByParentId1);
                            }
                        }

                    }


                    mProcedureAndModuleDto.setMprocedureVo(mProcedure);
                    mprocedureAndModuleDtos.add(mProcedureAndModuleDto);
                }
            }
            return ResultFactory.buildSuccessResult("查询成功", mprocedureAndModuleDtos);

        }


    }

    @Override
    public Result submitRegister(SubmitRegisterDto submitRegisterDto) {
        MProceduring mProceduring = new MProceduring();
        mProceduring.setParentId(submitRegisterDto.getMmanufacture().getId());
        mProceduring.setDetailsNumber(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getDetailsNumber());
        mProceduring.setProcedureId(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureId());
        mProceduring.setProcedureName(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureName());
        mProceduring.setLabourHourAmount(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours());
        mProceduring.setCostPrice(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getCostPrice());
        BigDecimal costPrice = submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getCostPrice();
        BigDecimal numberOfHours = submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours();
        mProceduring.setSubtotal(
                BigDecimal.valueOf(costPrice.doubleValue() * numberOfHours.doubleValue())
        );
        mProceduring.setRegister(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getRegister());
        mProceduring.setRegisterTime(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getRegisterTime());
        mProceduring.setProcedureResponsiblePerson(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getFunctionary());

        Integer regCount = mProceduringMapper.regCount(
                submitRegisterDto.getMmanufacture().getId(),
                Integer.parseInt(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureId()), submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureName());
        if (regCount == null) {
            mProceduring.setRegCount(BigDecimal.valueOf(1));
        } else {
            mProceduring.setRegCount(BigDecimal.valueOf(regCount + 1));
        }
        mProceduringMapper.insert(mProceduring);
        if (submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos() != null && submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos().size() > 0) {
            for (MProcedureModuleVo mprocedureModuleVo : submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos()) {
                if (mprocedureModuleVo.getNumber() != null) {
                    MProcedureModuling mProcedureModuling = new MProcedureModuling();
                    mProcedureModuling.setParentId(mProceduring.getId());
                    mProcedureModuling.setDetailsNumber(mprocedureModuleVo.getDetailsNumber());
                    mProcedureModuling.setProductId(mprocedureModuleVo.getProductId());
                    mProcedureModuling.setProductName(mprocedureModuleVo.getProductName());
                    mProcedureModuling.setCostPrice(mprocedureModuleVo.getCostPrice());
                    mProcedureModuling.setAmount(mprocedureModuleVo.getNumber());
                    mProcedureModuling.setSubtotal(BigDecimal.valueOf(mprocedureModuleVo.getCostPrice().doubleValue() *
                            mprocedureModuleVo.getNumber().doubleValue()));
                    mProcedureModulingMapper.insert(mProcedureModuling);
                }
            }
        }

        mProcedureMapper.updateProcedureFinishTagById(
                submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getId(),
                submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureFinishTag()
        );

        mManufactureMapper.updateManufactureProcedureTagById(submitRegisterDto.getMmanufacture().getId(), "S002-1");


        return ResultFactory.buildSuccessResult("登记成功,需要复核");

    }

    @Override
    public Result queryAllNotCheckProductionRegistrationByPage(Integer currNo, Integer pageSize) {
        int rowCount = mManufactureMapper.rowCountNotCheck();
        PageBean pageBean = new PageBean(pageSize, currNo, rowCount);
        List<MManufacture> allByRegisteredTobe = mManufactureMapper.getAllNotCheck(pageBean.getStart(), pageBean.getEnd());
        pageBean.setPageList(allByRegisteredTobe);
        return ResultFactory.buildSuccessResult("查询成功", pageBean);
    }

    @Override
    public Result check(SubmitRegisterDto submitRegisterDto) {
        boolean flag = true;
        List<MProceduring> allNotCheckByMmanufactureId = mProceduringMapper.getAllNotCheckByMmanufactureId(submitRegisterDto.getMmanufacture().getId());
        if (allNotCheckByMmanufactureId != null && allNotCheckByMmanufactureId.size() == 1) {
            List<MProcedure> allByParentId = mProcedureMapper.getAllByParentId(submitRegisterDto.getMmanufacture().getId());
            List<MProcedure> collect = allByParentId.stream().filter(m -> m.getProcedureTransferTag().equals("G005-1")).collect(Collectors.toList());
            if (collect == null || collect.size() <= 1) {
                mManufactureMapper.updateManufactureProcedureTagById(submitRegisterDto.getMmanufacture().getId(), "S002-0");
            }

            flag = false;
        }
        MManufacture mManufacture = new MManufacture();
        mManufacture.setId(submitRegisterDto.getMmanufacture().getId());
        double price = submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getCostPrice().doubleValue();
        double hours = submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours().doubleValue();
        if (hours > 0) {
            double v = submitRegisterDto.getMmanufacture().getRealLabourCostPriceSum() == null ? 0 : submitRegisterDto.getMmanufacture().getRealLabourCostPriceSum().doubleValue();
            mManufacture.setRealLabourCostPriceSum(BigDecimal.valueOf(v + price * hours));
        }
        double module = submitRegisterDto.getMmanufacture().getRealModuleCostPriceSum() == null ? 0 : submitRegisterDto.getMmanufacture().getRealModuleCostPriceSum().doubleValue();

        System.out.println(module);
        if (submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos() != null && submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos().size() > 0) {
            for (MProcedureModuleVo mprocedureModuleVo : submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos()) {
                if (mprocedureModuleVo.getNumber().doubleValue() > 0) {
                    mProcedureModulingMapper.updateAmountAndSubtotal(mprocedureModuleVo.getId(),
                            mprocedureModuleVo.getNumber().doubleValue(),
                            mprocedureModuleVo.getCostPrice().doubleValue() * mprocedureModuleVo.getNumber().doubleValue());
                    module += mprocedureModuleVo.getCostPrice().doubleValue() * mprocedureModuleVo.getNumber().doubleValue();
                } else {
                    mProcedureModulingMapper.deleteByPrimaryKey(mprocedureModuleVo.getId());
                }

            }
        }

        mManufacture.setRealModuleCostPriceSum(BigDecimal.valueOf(module));

        mManufactureMapper.updateByPrimaryKeySelective(mManufacture);

        MProceduring mProceduring = new MProceduring();

        mProceduring.setId(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getId());
        mProceduring.setLabourHourAmount(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours());
        mProceduring.setSubtotal(
                BigDecimal.valueOf(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getCostPrice().doubleValue() *
                        submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours().doubleValue())
        );
        mProceduring.setChecker(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getChecker());
        mProceduring.setCheckTime(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getCheckerTime());
        mProceduring.setProcedureResponsiblePerson(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getFunctionary());

        mProceduringMapper.updateByPrimaryKeySelective(mProceduring);

        List<MProcedure> allByParentId = mProcedureMapper.getAllByParentId(submitRegisterDto.getMmanufacture().getId());
        for (MProcedure mProcedure : allByParentId) {
            if (mProcedure.getProcedureName().equals(submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureName())) {
                Double v = mProcedure.getRealLabourHourAmount() == null ? 0 : mProcedure.getRealLabourHourAmount().doubleValue();

                double v1 = submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getNumberOfHours().doubleValue();
                Double realSubtotal = mProcedure.getRealSubtotal() == null ? 0 : mProcedure.getRealSubtotal().doubleValue();
                mProcedure.setRealSubtotal(BigDecimal.valueOf(realSubtotal + mProcedure.getCostPrice().doubleValue() * v1));
                mProcedure.setRealLabourHourAmount(BigDecimal.valueOf(v + v1));

                double sum = 0;
                for (MProcedureModuleVo mprocedureModuleVo : submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos()) {
                    if (mprocedureModuleVo.getNumber().doubleValue() > 0) {
                        sum += mprocedureModuleVo.getCostPrice().doubleValue() * mprocedureModuleVo.getNumber().doubleValue();
                    }

                }
                Double v2 = mProcedure.getRealModuleSubtotal() == null ? 0 : mProcedure.getRealModuleSubtotal().doubleValue();

                mProcedure.setRealModuleSubtotal(BigDecimal.valueOf(v2 + sum));
                if (submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureVo().getProcedureFinishTag().equals("G004-2")) {
                    mProcedure.setProcedureFinishTag("G004-0");
                } else {
                    mProcedure.setProcedureFinishTag("G004-3");
                }

                mProcedureMapper.updateByPrimaryKey(mProcedure);

                List<MProcedureModule> allByParentId1 = mProcedureModuleMapper.getAllByParentId(mProcedure.getId());
                for (MProcedureModule mProcedureModule : allByParentId1) {
                    for (MProcedureModuleVo mprocedureModuleVo : submitRegisterDto.getMprocedureVoAndModuleVoDto().getMprocedureModuleVos()) {
                        if (mProcedureModule.getProductName().equals(mprocedureModuleVo.getProductName()) && mprocedureModuleVo.getNumber().doubleValue() > 0) {
                            Double v3 = mProcedureModule.getRealAmount() == null ? 0 : mProcedureModule.getRealAmount().doubleValue();
                            double v4 = mprocedureModuleVo.getNumber().doubleValue();

                            mProcedureModule.setRealAmount(BigDecimal.valueOf(v3 + v4));
                            Double v5 = mProcedureModule.getRealSubtotal() == null ? 0 : mProcedureModule.getRealSubtotal().doubleValue();
                            double v6 = mProcedureModule.getCostPrice().doubleValue();

                            mProcedureModule.setRealSubtotal(BigDecimal.valueOf(v5 + v6 * v4));
                            mProcedureModuleMapper.updateByPrimaryKey(mProcedureModule);

                        }

                    }

                }

            }

        }

        return ResultFactory.buildSuccessResult("复核成功", flag);

    }

    @Override
    public Result transferRegister(Integer mmanufactureId, Integer mProcedureId, Double realAmount) {
        mManufactureMapper.updateManufactureProcedureTagById(mmanufactureId, "S002-1");
        mProcedureMapper.updateRealAmountAndTransferTag(mProcedureId, "G005-1", realAmount);
        return ResultFactory.buildSuccessResult("交接成功");

    }

    @Override
    public Result getRealAmount(Integer mProcedureId) {
        MProcedure mProcedure = mProcedureMapper.selectByPrimaryKey(mProcedureId);
        return ResultFactory.buildSuccessResult("查询成功", mProcedure);

    }

    @Override
    public Result transferAudit(Integer mmanufactureId, Integer mProcedureId, Double realAmount) {
        List<MProcedure> allByParentId = mProcedureMapper.getAllByParentId(mmanufactureId);
        List<MProcedure> collect = allByParentId.stream().filter(m -> m.getProcedureTransferTag().equals("G005-0") || m.getProcedureTransferTag().equals("G005-1")).collect(Collectors.toList());
        boolean flag = true;

        if (collect != null && collect.size() > 1) {
            flag = true;
            mManufactureMapper.updateManufactureProcedureTagById(mmanufactureId, "S002-1");
            mProcedureMapper.updateRealAmountAndTransferTag(mProcedureId, "G005-2", realAmount);

        } else {
            flag = false;
            MManufacture mManufacture = mManufactureMapper.selectByPrimaryKey(mmanufactureId);
            mManufacture.setManufactureProcedureTag("S002-2");
            mManufacture.setTestedAmount(BigDecimal.valueOf(realAmount));

            mManufactureMapper.updateByPrimaryKey(mManufacture);
            mProcedureMapper.updateRealAmountAndTransferTag(mProcedureId, "G005-2", realAmount);


            DFile dFile = dFileMapper.getByProductId(mManufacture.getProductId());
            SGather sGather = new SGather();
            sGather.setGatherId(SerialNumberUtil.godownEntrySerNumber());
            sGather.setReason("R001-1");
            sGather.setAmountSum(BigDecimal.valueOf(realAmount));
            double price = dFile.getCostPrice().doubleValue();

            sGather.setCostPriceSum(BigDecimal.valueOf(price * realAmount));
            sGather.setCheckTag("S001-1");
            sGather.setStoreTag("K002-1");
            sGatherMapper.insert(sGather);

            SGatherDetails sGatherDetails = new SGatherDetails();
            sGatherDetails.setParentId(sGather.getId());
            sGatherDetails.setProductId(dFile.getProductId());
            sGatherDetails.setProductName(dFile.getProductName());
            sGatherDetails.setProductDescribe(dFile.getProductDescribe());
            sGatherDetails.setAmountUnit(dFile.getAmountUnit());
            sGatherDetails.setCostPrice(dFile.getCostPrice());

            sGatherDetails.setGatherTag("K002-1");
            sGatherDetails.setAmount(BigDecimal.valueOf(realAmount));
            sGatherDetails.setSubtotal(BigDecimal.valueOf(sGatherDetails.getAmount().doubleValue()*sGatherDetails.getCostPrice().doubleValue()));
            sGatherDetailsMapper.insert(sGatherDetails);
//            SCell sCell = sCellMapper.getByProductId(dFile.getProductId());
//            sCell.setAmount(BigDecimal.valueOf(realAmount));
//            sCellMapper.updateByPrimaryKey(sCell);


        }
        return ResultFactory.buildSuccessResult("审核成功", flag);

    }
}
